package com.lyt.springboot.util.algorithm;

import java.util.PriorityQueue;

public class S11 {
    //定义大顶堆 和小顶堆
    PriorityQueue<Integer> min_heap = new PriorityQueue<>();
    PriorityQueue<Integer> max_heap = new PriorityQueue<>(((o1, o2) ->o2-o1 ));
    int count=0;
    public void Insert(Integer num) {
        //自定义左边是大顶堆，右边是小顶堆 不用在意排序 插入左边和插入右边一样
        //自己定义偶数放入小堆  奇数放入大堆
        //做大堆   右小堆    左.peek（）< 右.peek（）
        if(count%2==0) {
            max_heap.add(num);
            Integer temp = max_heap.poll();
            min_heap.add(temp);
//            min_heap.add(num);
//            Integer temp = min_heap.poll();
//            max_heap.add(temp);
        }else {
            min_heap.add(num);
            Integer temp = min_heap.poll();
            max_heap.add(temp);
//            max_heap.add(num);
//            Integer temp = max_heap.poll();
//            min_heap.add(temp);
        }
        count++;

    }

    public Double GetMedian() {
        if(count%2==0) {
            return new Double(min_heap.peek()+max_heap.peek())/2;

        }else {
            return new Double(min_heap.peek());
//            return new Double(max_heap.peek());
        }
    }

    public static void main(String[] args) {
        S11 s11 = new S11();
        s11.Insert(2);
        s11.Insert(8);
        s11.Insert(4);
        s11.Insert(5);
        s11.Insert(6);
        s11.Insert(10);
        s11.Insert(1);
        Double aDouble = s11.GetMedian();
        System.out.println(aDouble);

    }

}
